package edu.ntu.cloudroid.server.backendservice;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import edu.ntu.cloudroid.model.PMF;
import edu.ntu.cloudroid.model.friend.GroupData;
import edu.ntu.cloudroid.model.profile.ProfileData;

public class Utilities {
	public static ProfileData findPersonByKey(Key k)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.getFetchPlan().addGroup(ProfileData.FETCH_GROUP_NAME);
		pm.getFetchPlan().setMaxFetchDepth(2);

		try {
			ProfileData p = findPersonByKey(k, pm);
			return pm.detachCopy(p);
		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}
	}

	public static ProfileData findPersonByEmailAddress(String emailAddress)
	{
		return findPersonByKey(getPersonKey(emailAddress));
	}

	public static GroupData findGroupByKey(Key k)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.getFetchPlan().addGroup(GroupData.FETCH_GROUP_NAME);
		pm.getFetchPlan().setMaxFetchDepth(2);
		

		try {
			GroupData g = pm.getObjectById(GroupData.class, k);
			return pm.detachCopy(g);
		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}
	}

	public static GroupData findGroup(String personEmail, String groupName)
	{
		Key personKey = getPersonKey(personEmail);
		return findGroupByKey(getGroupKey(personKey, groupName));
	}
	
	private static ProfileData findPersonByKey(Key k, PersistenceManager pm)
	 {
		 return pm.getObjectById(ProfileData.class, k);
	 }

	 private static GroupData findGroupByKey(Key k, PersistenceManager pm)
	 {
		 return pm.getObjectById(GroupData.class, k);
	 }

	 static ProfileData findPersonByEmailAddress(String emailAddress,
			 PersistenceManager pm)
	 {
		 return findPersonByKey(getPersonKey(emailAddress), pm);
	 }

	 public static Key getPersonKey(String emailAddress)
	 {
		 return KeyFactory.createKey(ProfileData.class.getSimpleName(), emailAddress);
	 }

	 private static Key getGroupKey(Key personKey, String groupName)
	 {
		 return KeyFactory.createKey(personKey, GroupData.class.getSimpleName(),
				 groupName);
	 }
}
